package cn.net.autocode.platform.providers;

import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.platform.customDict.CustomDict;
import cn.net.autocode.platform.customDict.CustomDictAnnotation;
import cn.net.autocode.platform.factory.SpringBeanFactory;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/autocode/customDictProvider")
public class CustomDictProviderCtrl {

    private final Map<String,CustomDict> customDictMap = new HashMap<>();

    @PostMapping(value = "{dict}", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResultT dict(@PathVariable("dict") String dict, @RequestBody JSONObject param) {
        if(customDictMap.containsKey(dict)){
            CustomDict customDict = this.customDictMap.get(dict);
            return customDict.query(param);
        }else{
            CustomDict customDict = null;
            List<CustomDict> beans = SpringBeanFactory.getBeansByType(CustomDict.class);
            for (CustomDict bean : beans) {
                CustomDictAnnotation customDictAnnotation = bean.getClass().getAnnotation(CustomDictAnnotation.class);
                if (customDictAnnotation != null) {
                    String annotationName = customDictAnnotation.value();
                    if (annotationName.equals(dict)){
                        this.customDictMap.put(annotationName,bean);
                        customDict = bean;
                        break;
                    }
                }
            }
            if (customDict==null){
                throw new RuntimeException("没有定义"+dict+"字典值");
            }else{
                return customDict.query(param);
            }
        }
    }

}
